import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Layout, Table, Button, Form, Input, message, Modal } from 'antd';

const { Header, Content } = Layout;

const DataManage = () => {
  const [data, setData] = useState([]);
  const [editingKey, setEditingKey] = useState('');
  const [jsonModalVisible, setJsonModalVisible] = useState(false);
  const [jsonContent, setJsonContent] = useState('');
  const [form] = Form.useForm();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await axios.get('http://39.106.250.42:5172/get_dataset');
        setData(res.data);
      } catch (err) {
        console.error(err);
      }
    };

    fetchData();
  }, []);

  const isEditing = (record) => record.dataset_id === editingKey;

  const edit = (record) => {
    form.setFieldsValue({ ...record });
    setEditingKey(record.dataset_id);
  };

  const cancel = () => {
    setEditingKey('');
  };

  const save = async (dataset_id) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => dataset_id === item.dataset_id);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey('');

        await axios.post('http://39.106.250.42:5172/change_dataset', { dataset_id, ...row });
        message.success('Data saved successfully.');
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const deleteData = async (dataset_id) => {
    try {
      await axios.post('http://39.106.250.42:5172/del_dataset', { dataset_id });
  
      const newData = data.filter((item) => item.dataset_id !== dataset_id);
      setData(newData);
      message.success('Data deleted successfully.');
    } catch (err) {
      console.error('Failed to delete data:', err);
      message.error('Failed to delete data.');
    }
  };

  const showJsonModal = (json) => {
    setJsonContent(JSON.stringify(json, null, 2));
    setJsonModalVisible(true);
  };

  const columns = [
    {
      title: '数据类型',
      dataIndex: 'type',
      editable: false,
    },
    {
      title: '数据集ID',
      dataIndex: 'dataset_id',
      editable: true,
    },
    {
      title: '数据集名称',
      dataIndex: 'name',
      editable: true,
    },
    {
      title: '属性',
      dataIndex: 'attribute',
      editable: true,
    },
    {
      title: '可用',
      dataIndex: 'available',
      editable: true,
    },
    {
      title: 'JSON文件',
      dataIndex: 'jsonFile',
      render: (_, record) => (
        <Button onClick={() => showJsonModal(record.jsonFile)}>查看JSON</Button>
      ),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Button onClick={() => save(record.dataset_id)} style={{ marginRight: 8 }}>
              保存
            </Button>
            <Button onClick={cancel}>取消</Button>
          </span>
        ) : (
          <span>
            <Button onClick={() => edit(record)} style={{ marginRight: 8 }}>
              编辑
            </Button>
            <Button onClick={() => deleteData(record.dataset_id)} danger>
              删除
            </Button>
          </span>
        );
      },
    },
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{ margin: 0 }}
            rules={[
              {
                required: true,
                message: `Please Input ${title}!`,
              },
            ]}
          >
            <Input />
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  return (
    <div style={{ maxHeight: '100%', minHeight: '100%', overflow: 'scroll' }} className='data-manage-table'>
      <Form form={form} component={false}>
        <Table
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          rowHoverable="False"
          dataSource={data}
          columns={mergedColumns}
          rowClassName="editable-row"
          pagination={{ pageSize: 10 }}
          rowKey="dataset_id"
          scroll={{ x: 'max-content' }}
        />
      </Form>
      <Modal
        title="JSON 文件"
        visible={jsonModalVisible}
        onCancel={() => setJsonModalVisible(false)}
        footer={null}
        style={{backgroundColor:'rgba(16, 58, 91, 0.85)', borderRadius:'0', border:'1px solid rgba(126, 156, 179, 0.8)'}}
      >
        <pre>{jsonContent}</pre>
      </Modal>
    </div>
  );
};

export default DataManage;
